import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store';

Vue.use(VueRouter)

const routes = [
  {
    path: '/Login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/',  // 主路径
    redirect: '/Login'  // 直接重定向
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/AccountManagementView',
    name: 'AccountManagementView',
    component: () => import('../views/AccountManagementView.vue')
  },
  {
    path: '/CardManagementView',
    name: 'CardManagementView',
    component: () => import('../views/CardManagementView.vue')
  },
  {
    path: '/PublicizeManagementView',
    name: 'PublicizeManagementView',
    component: () => import('../views/PublicizeManagementView.vue')
  },
  {
    path: '/Permissions403View',
    name: 'Permissions403View',
    component: () => import('../views/Permissions403View.vue')
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters['user/isAuthenticated']; // 从 user 模块获取登录状态
  const userPermissions = store.getters['user/permissions']; // 从 user 模块获取权限列表

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      return next({ path: '/login' });
    }

    if (to.meta.requiredPermissions) {
      const hasPermission = to.meta.requiredPermissions.every(permission =>
        userPermissions.includes(permission)
      );
      if (!hasPermission) {
        return next({ path: '/403' }); // 跳转到权限不足页面
      }
    }
  }

  next();
});


export default router
